#include "lua_framework.hh"
#include "../../protocol_files/common/generated_proto_header.hh"

#include "../../corelib/util/os_util.hh"
#include "../../corelib/util/string_util.hh"
#include "../../plugin/base/rpc_base.hh"
#include "lua_bind.hh"
#include "../../protocol_files/lua_rpc/rpc_generated.hh"

LuaFramework::LuaFramework() {
}

LuaFramework::~LuaFramework() {
}

bool LuaFramework::onInstall(kconfig::Config * config) {
    static std::string ROOT_SCRIPT_NAME("root.lua");
    std::string rootScriptName = ROOT_SCRIPT_NAME;
    if (config->has("lua.path")) {
        rootPath_ = kratos::corelib::OS::completePath(getRootPath(), config->getString("lua.path"));
    } else {
        rootPath_ = getRootPath();
    }
    if (config->has("lua.path.rootScript")) {
        rootScriptName = config->getString("lua.path.rootScript");
    }
    rootPath_ = kratos::corelib::OS::completePath(rootPath_, rootScriptName);
    // Load protobuf files
    if (!RPCRef.loadPBProto(getRootPath())) {
        return false;
    }
    // Install RPC skeleton
    RPCSkeleton::install();
    return LuaRef.onInstall();
}

bool LuaFramework::onUninstall() {
    RPCSkeleton::uninstall();
    return LuaRef.onUninstall();
}

bool LuaFramework::onStart(kconfig::Config * config) {
    return LuaRef.onStart();
}

bool LuaFramework::onStop() {
    return LuaRef.onStop();
}

void LuaFramework::onTick(std::time_t millionseconds) {
    LuaRef.onTick(millionseconds);
}

void LuaFramework::onPathJoin(PathID pathID, SiteType siteType, UserData userData) {
    LuaRef.onPathJoin(pathID, siteType, userData);
}

void LuaFramework::onPathDisjoin(PathID pathID, SiteType siteType) {
    LuaRef.onPathDisjoin(pathID, siteType);
}

void LuaFramework::onFindPathTimeout(SiteType siteType, UserData userData) {
    LuaRef.onFindPathTimeout(siteType, userData);
}

void LuaFramework::onEntityFound(std::uint32_t type, const EntityIDVector& ids, std::uint64_t userData) {
    LuaRef.onEntityFound(type, ids, userData);
}

const std::string & LuaFramework::getRootScript() const {
    return rootPath_;
}
